package com.cheer.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.common.Page;
import com.cheer.dao.OaAdminDao;
import com.cheer.dto.OaAdminAddDTO;
import com.cheer.dto.OaAdminUpdateDTO;
import com.cheer.dto.PasswordUpdateDTO;
import com.cheer.entity.OaAdminEntity;
import com.cheer.entity.OaLearnClassEntity;
import com.cheer.exception.ServiceException;
import com.cheer.security.UserInfoHolder;
import com.cheer.service.OaAdminRoleService;
import com.cheer.service.OaAdminService;
import com.cheer.service.OaLearnClassService;
import com.cheer.vo.OaAdminInfoVO;
import com.cheer.vo.OaAdminListVO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("oaAdminService")
public class OaAdminServiceImpl extends ServiceImpl<OaAdminDao, OaAdminEntity> implements OaAdminService {

    @Autowired
    private OaAdminDao oaAdminDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private OaAdminRoleService oaAdminRoleService;

    @Autowired
    private OaLearnClassService oaLearnClassService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Override
    public OaAdminEntity getByPhone(String phone) {
        return oaAdminDao.selectByPhone(phone);
    }

    @Override
    public void add(OaAdminAddDTO adminAddDTO) {
        if (oaAdminDao.selectByPhone(adminAddDTO.getPhone())!=null){
            throw new ServiceException("您的账号已经注册，请直接登录，登陆后请完善信息");
        }

        if (adminAddDTO.getPid() == null) {
            adminAddDTO.setPid(0);
        } else if (adminAddDTO.getPid() != 0) {
            if (oaLearnClassService.getById(adminAddDTO.getPid()) == null) {
                throw new ServiceException("选择的单位不存在");
            }
        }

        if (oaAdminRoleService.getById(adminAddDTO.getRoleId()) == null) {
            throw new ServiceException("选择的权限不存在");
        }

        OaAdminEntity admin = new OaAdminEntity()
                .setAdName(adminAddDTO.getName())
                .setPname(adminAddDTO.getPname())
                .setAdTel(adminAddDTO.getPhone())
                .setAdPwd(passwordEncoder.encode(adminAddDTO.getPassword()))
                .setPid(adminAddDTO.getPid())
                .setRoleId(adminAddDTO.getRoleId());

        oaAdminDao.insert(admin);
    }

    @Override
    public Page<OaAdminListVO> list(Integer pageNum, Integer pageSize, String keyword) {
        IPage<OaAdminEntity> page = oaAdminDao.selectPage(pageNum, pageSize, keyword);

        List<OaAdminListVO> adminListVOList = page.getRecords().stream()
                .map(admin -> new OaAdminListVO()
                        .setId(admin.getId())
                        .setName(admin.getAdName())
                        .setPname(admin.getPname())
                        .setPhone(admin.getAdTel())
                        .setRole(admin.getRoleId())
                        .setStatus(admin.getStatus()))
                .collect(Collectors.toList());

        return new Page<>(page, adminListVOList);
    }

    @Override
    public void delete(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            oaAdminDao.deleteBatchIds(ids);
        }
    }

    @Override
    public OaAdminInfoVO info(Integer id) {
        OaAdminEntity admin = oaAdminDao.selectById(id);
        if (admin == null) {
            throw new ServiceException("管理员不存在");
        }

        OaAdminInfoVO adminInfoVO = new OaAdminInfoVO()
                .setId(admin.getId())
                .setName(admin.getAdName())
                .setPhone(admin.getAdTel())
                .setPname(admin.getPname())
                .setRole(admin.getRoleId());

        if (admin.getPid() == 0) {
            adminInfoVO.setPath(Lists.newArrayList(0));
        } else {
            OaLearnClassEntity learnClass = oaLearnClassService.getById(admin.getPid());
            if (learnClass == null) {
                throw new ServiceException("所在单位已删除");
            } else {
                String[] split = StringUtils.split(learnClass.getPath(), ",");
                List<Integer> path = new ArrayList<>();
                if (ArrayUtils.isNotEmpty(split)) {
                    for (String str : split) {
                        if (!StringUtils.equals("0", str)) {
                            path.add(Integer.valueOf(str));
                        }
                    }
                }
                path.add(admin.getPid());
                adminInfoVO.setPath(path);
            }
        }

        return adminInfoVO;
    }

    @Override
    public void deleteByPid(Integer pid) {
        oaAdminDao.deleteByPid(pid);
    }

    @Override
    public void update(OaAdminUpdateDTO adminUpdateDTO) {
        OaAdminEntity admin = oaAdminDao.selectById(adminUpdateDTO.getId());
        if (admin == null) {
            throw new ServiceException("管理员不存在");
        }

        if (adminUpdateDTO.getPid() == null) {
            adminUpdateDTO.setPid(0);
        } else {
            if (oaLearnClassService.getById(adminUpdateDTO.getPid()) == null) {
                throw new ServiceException("选择的单位不存在");
            }
        }

        if (oaAdminRoleService.getById(adminUpdateDTO.getRoleId()) == null) {
            throw new ServiceException("选择的权限不存在");
        }

        OaAdminEntity updateAdmin = new OaAdminEntity()
                .setId(adminUpdateDTO.getId())
                .setAdName(adminUpdateDTO.getName())
                .setPname(adminUpdateDTO.getPname())
                .setAdTel(adminUpdateDTO.getPhone())
                .setPid(adminUpdateDTO.getPid())
                .setRoleId(adminUpdateDTO.getRoleId());

        oaAdminDao.updateById(updateAdmin);
    }

    @Override
    public void reset(Integer id) {
        OaAdminEntity admin = oaAdminDao.selectById(id);
        if (admin == null) {
            throw new ServiceException("管理员不存在");
        }

        OaAdminEntity updateAdmin = new OaAdminEntity()
                .setId(id)
                .setAdPwd(passwordEncoder.encode("000000"));

        oaAdminDao.updateById(updateAdmin);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        OaAdminEntity admin = oaAdminDao.selectById(id);
        if (admin == null) {
            throw new ServiceException("管理员不存在");
        }

        OaAdminEntity updateAdmin = new OaAdminEntity()
                .setId(id)
                .setStatus(status);

        oaAdminDao.updateById(updateAdmin);
    }

    @Override
    public void updatePassword(PasswordUpdateDTO passwordUpdateDTO) {
        String username = userInfoHolder.getAdmin().getAdTel();
        OaAdminEntity admin = oaAdminDao.selectByPhone(username);
        if (admin == null) {
            throw new ServiceException("帐号不存在");
        }

        if (!passwordEncoder.matches(passwordUpdateDTO.getOldPassword(), admin.getAdPwd())) {
            throw new ServiceException("旧密码输入错误");
        }

        OaAdminEntity updateAdmin = new OaAdminEntity()
                .setId(admin.getId())
                .setAdPwd(passwordEncoder.encode(passwordUpdateDTO.getNewPassword()));

        oaAdminDao.updateById(updateAdmin);
    }
}